package cn.com.gridinfo.sooc.core.my.personal.activity;

import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.view.KeyEvent;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.jeremy.arad.Arad;
import com.jeremy.arad.utils.StringUtils;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import butterknife.OnTextChanged;
import cn.com.gridinfo.sooc.R;
import cn.com.gridinfo.sooc.base.BaseSoocActivity;
import cn.com.gridinfo.sooc.common.LocalMark;
import cn.com.gridinfo.sooc.core.my.commen.CodeConst;
import cn.com.gridinfo.sooc.core.my.dao.MyDao;
import cn.com.gridinfo.sooc.utils.MessageUtils;
import cn.com.gridinfo.sooc.utils.widget.ClearEditText;

/**
 * 绑定手机号
 * Created by 刘晓晨 on 2015/12/17.
 */
public class ChangeCellNumberActivity extends BaseSoocActivity {


    @InjectView(R.id.edit_cellphone)// （*绑定界面）输入手机号
            ClearEditText editCellphone;
    @InjectView(R.id.edit_yzm)//（＊绑定界面）输入验证码
            ClearEditText editYzm;
    @InjectView(R.id.getCode)//(*绑定界面）获取验证码
            Button getCode;
    @InjectView(R.id.password)// (*绑定界面）输入密码验证
            ClearEditText password;
    @InjectView(R.id.btn_send)// （*绑定界面）提交 按钮
            Button btnSend;
    MyDao dao;
    private String imei;//手机识别码
    private String title;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_change_cellnumber);
        ButterKnife.inject(this);
        dao = new MyDao(this);
        if (StringUtils.isNull(getIntent().getStringExtra("noBoundCellPhone"))) {
            //如果为空 说明绑定了手机号，
            title = "更换手机号";
        } else {
            title = "绑定手机号";
        }
        try {
            TelephonyManager telephonyManager = (TelephonyManager) this.getSystemService(TELEPHONY_SERVICE);
            imei = telephonyManager.getDeviceId();//拿到识别码
        } catch (SecurityException e) {
            e.printStackTrace();
        } finally {
            if (imei == null || "".equals(imei)) {
                imei = Settings.Secure.getString(this.getContentResolver(), Settings.Secure.ANDROID_ID);
            }
        }
        btnSend.setEnabled(false);//不能点击时的状态
        getCode.setEnabled(false);
        password.setImeOptions(EditorInfo.IME_ACTION_DONE);
        password.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    if (validateNotNull()) {
                        onBound();
                    }
                }
                return false;
            }
        });
    }

    private boolean validateNotNull() {
        if (StringUtils.isNull(editCellphone.getText().toString().trim())) {
            editCellphone.requestFocus();
            return false;
        }
        if (StringUtils.isNull(editYzm.getText().toString().trim())) {
            editYzm.requestFocus();
            return false;
        }
        if (StringUtils.isNull(password.getText().toString().trim())) {
            password.requestFocus();
            return false;
        }
        return true;
    }

    //设置标题
    @Override
    public String setupToolBarTitle() {
        return title;

    }

    //设置左边按钮
    @Override
    public boolean setupToolBarLeftButton(ImageView leftButton) {
        return true;
    }

    //返回
    @OnClick(R.id.toolbar_leftbtn)
    void onGoBack() {

        finish();

    }

    private String pnumber;

    //点击获取验证码
    @OnClick(R.id.getCode)
    void getCode() {
        pnumber = editCellphone.getText().toString().trim();
        if (StringUtils.isNull(pnumber)) {
            MessageUtils.showImageShortToast(this, "请输入手机号");
        } else {
            //请求接口
            dao.getYzm(pnumber, 3, Build.VERSION.RELEASE, Build.MODEL, imei);
        }
    }

    //倒计时
    private CountDownTimer timer = new CountDownTimer(59000, 1000) {
        //点击后倒计时
        @Override
        public void onTick(long millisUntilFinished) {
            getCode.setEnabled(false);//不能点击
            getCode.setClickable(false);
            getCode.setText("重新发送" + (millisUntilFinished / 1000) + "s");
        }

        @Override
        public void onFinish() {
            getCode.setEnabled(true);
            getCode.setClickable(true);
            getCode.setText("重新发送");
        }
    };

    //点击绑定手机号
    @OnClick(R.id.btn_send)
    void onBound() {
        pnumber = editCellphone.getText().toString().trim();
        int yzm = Integer.parseInt(editYzm.getText().toString());
        String pass = password.getText().toString().trim();
        dao.onBound(pnumber, yzm, null, pass);
    }

    //请求成功
    @Override
    public void onRequestSuccess(int requestCode) {
        try {
            if (dao.status.equals("0")) {
                switch (requestCode) {
                    case CodeConst.GETSHOUJIYZM:
                        //获取验证码
                        timer.start();//启动计时器
                        MessageUtils.showRightImageShortToast(this, "验证码发送成功");
                        break;
                    case CodeConst.ONBOUND:
                        if (dao.status.equals("0")) {
                            MessageUtils.showRightImageShortToast(this, dao.statusCode);
                            Arad.preferences.putString(LocalMark.USER_TEL.getName(), pnumber);
                            Arad.preferences.flush();
                            if (OnBoundCellNumberActivity.instance != null) {
                                OnBoundCellNumberActivity.instance.finish();
                            }
                            setResult(RESULT_OK);
                            finish();
                        } else {
                            MessageUtils.showImageShortToast(this, dao.statusCode);
                        }
                        break;
                }
            } else {
                MessageUtils.showImageShortToast(this, dao.statusCode);
            }
        } catch (Exception e) {
            MessageUtils.showImageShortToast(this, "数据请求异常");
        }
    }

    @Override
    public void onRequestFaild(int requestCode, String errorNo, String errorMessage) {
        super.onRequestFaild(requestCode, errorNo, errorMessage);
        MessageUtils.showImageShortToast(this, dao.statusCode);
    }

    //设置手机号输入框的状态，有内容才可点击获取验证码
    @OnTextChanged(value = R.id.edit_cellphone, callback = OnTextChanged.Callback.AFTER_TEXT_CHANGED)
    void onAfterTextChanged2() {
        if (editCellphone.getText().toString().length() == 11) {
            getCode.setEnabled(true);
        } else {
            getCode.setEnabled(false);
        }
    }

    //设置输入框状态的监听，有内容的时候才可以点击提交按钮
    @OnTextChanged(value = {R.id.edit_cellphone, R.id.edit_yzm, R.id.password},
            callback = OnTextChanged.Callback.AFTER_TEXT_CHANGED)
    void onAfterTextChanged() {
        if (StringUtils.isNull(editCellphone.getText().toString()) ||
                StringUtils.isNull(editYzm.getText().toString()) ||
                StringUtils.isNull(password.getText().toString())) {
            btnSend.setEnabled(false);
        } else {
            btnSend.setEnabled(true);
        }
    }

}
